package cn.ytr.crm.util;

import cn.ytr.crm.domain.Employee;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

//用来操作 session 或拿客户端的信息等的工具类
public abstract class UserContext {

    //常量：员工的 session（登陆者信息 session）
    public static final String EMP_IN_SESSION = "EMP_IN_SESSION";
    //常量：员工的所有权限 session（登陆者拥有的权限 session）
    public static final String EMP_PERMISSION_IN_SESSION = "EMP_PERMISSION_IN_SESSION";

    //供外界用：把对象存到 session 的 key=EMP_IN_SESSION 里
    public static void setCurrentUser(Employee employee) {
        getSession().setAttribute(EMP_IN_SESSION, employee);
    }
    //供外界用：把该用户拥有的所有权限存到 session 的 key=EMP_PERMISSIONS_IN_SESSION 里
    public static void setCurrentUserPermission(List<String> permissions) {
        getSession().setAttribute(EMP_PERMISSION_IN_SESSION, permissions);
    }

    //供外界用：从 session 里获取 employee 对象
    public static Employee getCurrentUser() {
        return (Employee) getSession().getAttribute(EMP_IN_SESSION);
    }
    //供外界用：从 session 里获取 employee 对象
    public static List getCurrentUserPermission() {
        return (List) getSession().getAttribute(EMP_PERMISSION_IN_SESSION);
    }
    //供外界用：从 shiro 里获取 employee 对象
    public static Employee getCurrentUserByShiro() {
        //获取访问主体
        Subject subject = SecurityUtils.getSubject();
        //获取身份信息 employee 对象
        Employee employee = (Employee)subject.getPrincipal();
        return employee;
    }

    //供外界用：(通用)用来获取请求里的所有 session 的
    public static HttpSession getSession() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes.getRequest().getSession();
    }
}
